# "Media's Influence on LGBTQ Support Across Africa" by Stephen Winkler

# Code to setup R profile, run this prior to any other code in the project
# (this code was adapted from Jeffrey Arnold) 

# commonly loaded packages
suppressPackageStartupMessages({
  library("tidyverse")
  library("forcats")
  library("stringr")
  library("haven")
  library("rprojroot")
  library("magrittr")
  library("assertthat")
})

#' Root Directory of the Project
PROJECT_ROOT <- rprojroot::find_rstudio_root_file()

#' Project Path
project_path <- function(...) {
  file.path(PROJECT_ROOT, ...)
}

#' Add comments to a list
add_description <- function(.data, description) {
  attr(.data, "description") <- description
  .data
}

get_description <- function(.data) {
  attr(.data, "description")
}

drop_comments <- function(.data) {
  comment(.data) <- NULL
  mutate_each(.data, funs(~ `comment<-`(.x, NULL)))
}

#' Check if a data frame has comments on all its columns and the object itself
#' I use this to check that I've documented saved R objects
has_comments <- function(x, cols = TRUE, obj = TRUE) {
  obj_comment <- !obj | (x %has_attr% "comment")
  #cols_comments <- !cols | all(map_lgl(x, has_attr, "comment"))
  obj_comment & cols_comments
}

data_exists <- function(x, commented = TRUE) {
  assert_that(is.tbl(x))
  assert_that(nrow(x) > 0)
  assert_that(ncol(x) > 0)
  invisible(x)
}

fct_rm_levels <- function(f, levels = character()) {
  f <- forcats:::check_factor(f)
  new_levels <- levels(f)
  new_levels[new_levels %in% levels] <- NA_integer_
  lvls_revalue(f, new_levels)
}

add_session_info <- function(.data) {
  attr(.data, "sessionInfo") <- sessionInfo()
  .data
}

get_session_info <- function(.data) {
  attr(.data, "sessionInfo")
}

# load other packages used in analysis 
library(forcats)
library(tidyverse)
library(magrittr)
library(haven)
library(stringr)
library(dplyr)
library(simcf)
library(broom)
library(multiwayvcov)
library(lmtest)
library(stargazer)
library(margins)
library(MASS) #polr to run probit models
library(xtable)
library(ggthemes) #for map
library(lme4) #multilevel models
library(caret) #dummyVars 
library(naniar) #to replace values with NA
